import { Options } from '../entity/Options';
import fs from 'node:fs';
import { log } from './log';
import { resolve } from 'node:path';
import { getZipFullName } from './parameter';
import progress from 'cli-progress';
import * as https from 'https';

export async function download(options: Options) {
  let zipFullName = getZipFullName(options);
  let cacheFilePath = resolve(`${options.cacheDir}/${zipFullName}`);
  log.debug(`压缩包本地路径: '${cacheFilePath}'`);

  if (fs.existsSync(cacheFilePath) && fs.statSync(cacheFilePath).size < 1000) {
    log.debug('压缩包本地已存在但是太小，可能是下载错误，即将删除并重新下载');
    fs.rmSync(cacheFilePath);
    log.info('压缩包删除成功');
  }

  if (!fs.existsSync(cacheFilePath)) {
    let url = `${options.downloadUrl}/v${options.version}/${zipFullName}`;
    log.debug(`压缩包即将下载，下载地址: ${url}`);
    const bar = new progress.SingleBar({}, progress.Presets.rect);

    let out = resolve(cacheFilePath);
    const stream = fs.createWriteStream(out);


    await new Promise<void>((res, rej) => {


      https.get(url, response => {

        if (response.headers.location) {
          url = response.headers.location;
        }
        https.get(url, response1 => {
          let chunks = 0;
          bar.start(Number(response1.headers['content-length']), 0);
          response1.on('data', (chunk) => {
            chunks += chunk.length;
            bar.increment();
            bar.update(chunks);
          });

          response1.on('error', (error) => {
            rej(error);
          });

          response1.on('end', () => {
            bar.stop();
            res();
            log.debug('压缩包下载成功');
          });

          response1.pipe(stream);
        });
        response.on('error', (error) => {
          rej(error);
        });
      });

    });
  } else {
    log.debug('压缩包已存在，无需下载');
  }
}
